package _02datastructure
/*
映射
 */

//key可以自动转换成不可变的字符串
users = [
        fauks: '001',
        bob  : '002'
] //as HashMap 可以使用as操作符转换为自己想要的map
//默认为class java.util.LinkedHashMap
//.操作符是通过key取值，所以此处需要使用get方法
println users.getClass()

//取值
println users['fauks']
println users.bob
//添加元素
users.jay = '003'
//还可以直接添加另一个map（任意类型）
users.names = ['sex': 1, 'name': 'mj']
println users

students = [
        1: [no: '001', name: 'slx', score: 30, sex: 'male'],
        2: [no: '002', name: 'jay', score: 70, sex: 'male'],
        3: [no: '003', name: 'mary', score: 90, sex: 'female'],
        4: [no: '004', name: 'hong', score: 50, sex: 'female']
]
//遍历操作
students.each { stu ->
    println "key is ${stu.key},value is ${stu.value}"
}
//直接带key、value遍历
students.each {
    key, value -> println "key=${key},value=${value}"
}
students.eachWithIndex { entry, int i ->
    println "index=${i},key=${entry.key},value=${entry.value.name}"
}

//查找
//查找分数大于60的学生
def find = students.findAll { stu -> stu.value.score > 60 }
println "分数大于60的学生${find.toMapString()}"

//分数大于60的男生数量
println students.count { stu ->
    stu.value.sex == 'male' && stu.value.score > 60
}

//打印分数大于60学生姓名
def names = students.findAll { def stu ->
    return stu.value.score > 60
}.collect {
    //将map转换为一个list
    return it.value.name
}

println names.toListString()

//分组（按照分数分成及格与不及格）
def by = students.groupBy { stu ->
    return stu.value.score >= 60 ? '及格' : '不及格'
}
println by
//排序(同list)
//自定义排序：按照score排序
//不同于list在原有对象上修改，map排序后会返回新的对象所以需要重新赋值
students = students.sort { stu1, stu2 ->
    Number score1 = stu1.value.score
    Number score2 = stu2.value.score
    return score1 == score2 ? 0 : score1 > score2 ? 1 : -1
}
println students.collect { stu -> stu.value.name + ":" + stu.value.score }
